package com.picrepo.task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

import com.picrepo.app.AppData;
import com.picrepo.util.PicUtil;

public class UploadTask extends AsyncTask<String, Integer, String>
{
	private static final String TAG = "Vtag";
	
	private OnUploadListerner mOnUploadListerner;
	
	/**
	 * The login listener interface.
	 */
	public interface OnUploadListerner {
		/**
		 * Invoked when upload successfully.
		 */
		void onSuccess(String result);
		/**
		 * Invoked when fail to upload.
		 */
		void onFailure();
	}
	
	/**
	 * Set upload listener.
	 * 
	 * @param l the upload listener
	 */
	public void setOnUploadListerner(OnUploadListerner l) {
		this.mOnUploadListerner = l;
	}
	
	@Override
	protected String doInBackground(String... params) {
		HttpClient httpClient = new DefaultHttpClient();
		final HttpPost httpPost = new HttpPost(AppData.UPLOAD_POST_URL);
		final MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
		
		entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		entityBuilder.setCharset(Charset.forName(HTTP.UTF_8));
		
		String username = params[0];
		String filePath = params[1];
		/* transfer the picture to json string */
		Map<String, String> fileinfo = new HashMap<String, String>();
		fileinfo.put("filecontent", PicUtil.bitmapToString(
				PicUtil.getSmallBitmap(filePath)));
		String jsonString = new JSONObject(fileinfo).toString();
		StringBody strbody = new StringBody(jsonString, ContentType.APPLICATION_JSON);
		
		entityBuilder.addPart("fileinfo", strbody);
		entityBuilder.addTextBody("username", username);
		
		HttpEntity httpEntity = entityBuilder.build();
		
		httpPost.setEntity(httpEntity);
		try {
			HttpResponse response = httpClient.execute(httpPost);
			final int code = response.getStatusLine().getStatusCode();
			if (code == HttpStatus.SC_OK) {
				BufferedReader br = new BufferedReader(
						new InputStreamReader(response.getEntity().getContent()));
				StringBuilder builder = new StringBuilder();
				
	            String line;
	            while ((line = br.readLine()) != null) {
	            	builder.append(line+"\n");
	            }
	            br.close();
	          
	            return builder.toString();
			}
			
		} catch (ClientProtocolException e) {
			Log.d(TAG, "upload: " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			Log.d(TAG, "upload: " + e.getMessage());
			e.printStackTrace();
		} finally {
			if (httpClient != null) {
				httpClient.getConnectionManager().shutdown();
				httpClient = null;
			}
		}
		
		return null;
	}
	
	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		
		if (mOnUploadListerner != null) {
			if (result == null) {
				mOnUploadListerner.onFailure();
			} else {
				mOnUploadListerner.onSuccess(result);
			}
		}
	}
}
